package com.sinogrand.elevator.ui.components

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.material3.pulltorefresh.PullToRefreshContainer
import androidx.compose.material3.pulltorefresh.rememberPullToRefreshState
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.zIndex
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import androidx.compose.runtime.rememberCoroutineScope
import coil.compose.AsyncImage
import com.sinogrand.elevator.utils.PaginationUtils
import com.sinogrand.elevator.data.models.PageInfo
import com.sinogrand.elevator.data.models.ElevatorItem as ApiElevatorItem
import com.sinogrand.elevator.repository.ElevatorRepository
import androidx.compose.ui.platform.LocalContext
import android.util.Log
import com.sinogrand.elevator.utils.LogTags
import com.sinogrand.elevator.utils.Constants

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ElevatorListTab(
    project: ProjectItem,
    onElevatorClick: (ApiElevatorItem) -> Unit = {}
) {
    val context = LocalContext.current
    val elevatorRepository = remember { ElevatorRepository(context) }
    
    var isRefreshing by remember { mutableStateOf(false) }
    var isLoadingMore by remember { mutableStateOf(false) }
    var canLoadMore by remember { mutableStateOf(true) }
    var currentPage by remember { mutableStateOf(1) }
    var searchQuery by remember { mutableStateOf("") }
    var isSearching by remember { mutableStateOf(false) }
    var isLoading by remember { mutableStateOf(true) }
    var errorMessage by remember { mutableStateOf<String?>(null) }
    
    val listState = rememberLazyListState()
    val pullRefreshState = rememberPullToRefreshState()
    val coroutineScope = rememberCoroutineScope()
    
    // 电梯数据
    var elevators by remember { mutableStateOf<List<ApiElevatorItem>>(emptyList()) }
    var currentPageInfo by remember { mutableStateOf<PageInfo?>(null) }
    
    // 加载电梯数据
    suspend fun loadElevators(page: Int = 1, searchNo: String? = null, isRefresh: Boolean = false) {
        try {
            Log.d(LogTags.ELEVATOR_LIST, "开始加载项目电梯数据，项目ID: ${project.id}, 页码: $page")
            if (isRefresh) {
                isRefreshing = true
            } else if (page == 1) {
                isLoading = true
            } else {
                isLoadingMore = true
            }
            errorMessage = null

            val result = elevatorRepository.getProjectElevatorList(
                projectId = project.id.toInt(),
                page = page,
                size = 10,
                no = searchNo
            )
            
            if (result.isSuccess) {
                val data = result.getOrNull()
                if (data != null) {
                    if (isRefresh || page == 1) {
                        elevators = data.list
                        currentPage = 1
                        currentPageInfo = data.page_info
                        canLoadMore = PaginationUtils.hasNextPage(data.page_info)
                        Log.i(LogTags.ELEVATOR_LIST, "✅ 成功加载电梯数据: ${data.list.size}条，分页信息: page=${data.page_info.page}, size=${data.page_info.size}, total=${data.page_info.total}")
                    } else {
                        elevators = elevators + data.list
                        currentPageInfo = data.page_info
                        canLoadMore = PaginationUtils.hasNextPage(data.page_info)
                        Log.i(LogTags.ELEVATOR_LIST, "✅ 成功加载更多电梯数据: ${data.list.size}条，累计: ${elevators.size}条，分页信息: page=${data.page_info.page}, size=${data.page_info.size}, total=${data.page_info.total}")
                    }
                }
            } else {
                val exception = result.exceptionOrNull()
                Log.e(LogTags.ELEVATOR_LIST, "❌ 加载电梯数据失败: ${exception?.message}")
                errorMessage = "加载失败: ${exception?.message ?: "未知错误"}"
            }
        } catch (e: Exception) {
            Log.e(LogTags.ELEVATOR_LIST, "💥 加载电梯数据异常: ${e.message}", e)
            errorMessage = "网络异常: ${e.message}"
        } finally {
            isLoading = false
            isRefreshing = false
            isLoadingMore = false
        }
    }
    
    fun handleLoadMore() {
        if (!canLoadMore || isLoadingMore) return
        coroutineScope.launch {
            loadElevators(page = currentPage + 1, searchNo = if (searchQuery.isBlank()) null else searchQuery)
        }
    }
    
    fun handleSearch(query: String) {
        searchQuery = query
        isSearching = true
        
        coroutineScope.launch {
            delay(300) // 防抖延迟
            loadElevators(page = 1, searchNo = if (query.isBlank()) null else query)
            isSearching = false
        }
    }
    
    fun handleRefresh() {
        coroutineScope.launch {
            loadElevators(page = 1, searchNo = if (searchQuery.isBlank()) null else searchQuery, isRefresh = true)
        }
    }
    
    // 下拉刷新
    if (pullRefreshState.isRefreshing) {
        LaunchedEffect(true) {
            handleRefresh()
            pullRefreshState.endRefresh()
        }
    }
    
    // 上拉加载更多
    LaunchedEffect(listState) {
        snapshotFlow { listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index }
            .collect { lastVisibleIndex ->
                if (lastVisibleIndex != null && 
                    lastVisibleIndex >= elevators.size - 1 && 
                    canLoadMore && 
                    !isLoadingMore &&
                    elevators.isNotEmpty()) { // 确保列表不为空
                    handleLoadMore()
                }
            }
    }
    
    // 初始加载
    LaunchedEffect(Unit) {
        if (elevators.isEmpty()) {
            loadElevators()
        } else {
            isLoading = false
        }
    }
    
    Box(
        modifier = Modifier
            .fillMaxSize()
            .nestedScroll(pullRefreshState.nestedScrollConnection)
    ) {
        Column {
            // 简化的搜索框
            SearchBar(
                query = searchQuery,
                onQueryChange = { searchQuery = it },
                onSearch = { handleSearch(searchQuery) },
                onClear = {
                    searchQuery = ""
                    handleSearch("")
                },
                placeholder = "搜索梯号",
                isSearching = isSearching,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp)
                    .height(48.dp)
            )
            
            // 电梯列表
            LazyColumn(
                state = listState,
                modifier = Modifier
                    .fillMaxSize()
                    .padding(horizontal = 16.dp),
                verticalArrangement = Arrangement.spacedBy(8.dp),
                contentPadding = PaddingValues(
                    top = 8.dp,
                    bottom = 16.dp
                )
            ) {
                if (elevators.isEmpty()) {
                    item {
                        if (errorMessage != null) {
                            EmptyState(
                                title = "加载失败",
                                description = errorMessage!!
                            )
                        } else if (searchQuery.isBlank()) {
                            EmptyState(
                                title = "暂无电梯",
                                description = "当前项目还没有电梯数据"
                            )
                        } else {
                            EmptyState(
                                title = "没有找到电梯",
                                description = "没有找到包含\"$searchQuery\"的电梯"
                            )
                        }
                    }
                } else {
                    items(elevators.size) { index ->
                        val elevator = elevators[index]
                        ElevatorItemCard(
                            elevator = elevator,
                            onClick = { onElevatorClick(elevator) }
                        )
                    }
                }
                
                // 加载更多指示器
                if (isLoadingMore && searchQuery.isBlank()) {
                    item {
                        LoadingIndicator()
                    }
                }
                
                // 没有更多数据提示
                if (!canLoadMore && elevators.isNotEmpty() && searchQuery.isBlank()) {
                    item {
                        NoMoreDataIndicator()
                    }
                }
            }
        }
        
        // 下拉刷新容器 - 只在需要时显示
        if (pullRefreshState.isRefreshing || pullRefreshState.progress > 0f) {
            PullToRefreshContainer(
                state = pullRefreshState,
                modifier = Modifier
                    .align(Alignment.TopCenter)
                    .zIndex(1f) // 确保在列表内容之上
            )
        }
    }
}

enum class ElevatorStatus(val displayName: String, val color: Color) {
    NORMAL("正常", Color(0xFF10B981)),
    MAINTENANCE("维保中", Color(0xFFF59E0B)),
    FAULT("故障", Color(0xFFEF4444)),
    STOPPED("停用", Color(0xFF6B7280))
}

// 根据状态码获取状态信息
fun getElevatorStatus(status: Int): ElevatorStatus {
    return when (status) {
        1 -> ElevatorStatus.NORMAL
        2 -> ElevatorStatus.MAINTENANCE
        3 -> ElevatorStatus.FAULT
        4 -> ElevatorStatus.STOPPED
        else -> ElevatorStatus.NORMAL
    }
}

@Composable
fun ElevatorItemCard(
    elevator: ApiElevatorItem,
    onClick: () -> Unit
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .clickable { onClick() },
        colors = CardDefaults.cardColors(
            containerColor = Color.White
        ),
        elevation = CardDefaults.cardElevation(
            defaultElevation = 2.dp,
            pressedElevation = 4.dp
        ),
        shape = RoundedCornerShape(12.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            // 左侧图片
            Box(
                modifier = Modifier
                    .size(60.dp)
                    .clip(RoundedCornerShape(8.dp))
                    .background(Color(0xFFF3F4F6)),
                contentAlignment = Alignment.Center
            ) {
                if (elevator.imageUrl != null) {
                    AsyncImage(
                        model = elevator.imageUrl,
                        contentDescription = null,
                        modifier = Modifier
                            .fillMaxSize()
                            .clip(RoundedCornerShape(8.dp)),
                        contentScale = ContentScale.Crop
                    )
                } else {
                    Icon(
                        imageVector = Icons.Default.Elevator,
                        contentDescription = null,
                        modifier = Modifier.size(24.dp),
                        tint = Color(0xFF9CA3AF)
                    )
                }
            }
            
            Spacer(modifier = Modifier.width(12.dp))
            
            // 中间内容
            Column(
                modifier = Modifier.weight(1f)
            ) {
                // 顶部显示梯号
                Text(
                    text = elevator.no,
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Bold,
                    color = Color(0xFF1F2937),
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
                
                Spacer(modifier = Modifier.height(4.dp))
                
                // 下面显示电梯名称
                Text(
                    text = elevator.name,
                    fontSize = 14.sp,
                    color = Color(0xFF6B7280),
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
            }
            
            // 右侧状态标签
            val statusText = Constants.ElevatorStatus.getStatusDescription(elevator.status)
            val statusColor = when (elevator.status) {
                Constants.ElevatorStatus.DELETED -> Color(0xFF6B7280) // 灰色 - 删除
                Constants.ElevatorStatus.CONTRACT_PENDING -> Color(0xFFF59E0B) // 橙色 - 合同审批中
                Constants.ElevatorStatus.DISABLED -> Color(0xFFEF4444) // 红色 - 已禁用
                Constants.ElevatorStatus.WAITING_ALLOCATION -> Color(0xFF8B5CF6) // 紫色 - 待分配
                Constants.ElevatorStatus.ALLOCATION_PENDING -> Color(0xFFF59E0B) // 橙色 - 分配审核中
                Constants.ElevatorStatus.WAITING_START -> Color(0xFF3B82F6) // 蓝色 - 待开工
                Constants.ElevatorStatus.SAMPLE_DRAWING -> Color(0xFF10B981) // 绿色 - 放样中
                Constants.ElevatorStatus.SLOW_CAR_DEBUGGING -> Color(0xFF10B981) // 绿色 - 慢车调试
                Constants.ElevatorStatus.TRACK_DOOR_INSTALLATION -> Color(0xFF10B981) // 绿色 - 导轨厅门安装
                Constants.ElevatorStatus.FAST_CAR_DEBUGGING -> Color(0xFF10B981) // 绿色 - 快车调试
                Constants.ElevatorStatus.ACCEPTANCE -> Color(0xFF10B981) // 绿色 - 验收中
                Constants.ElevatorStatus.TRANSFER -> Color(0xFF10B981) // 绿色 - 移交中
                Constants.ElevatorStatus.ARCHIVE_PENDING -> Color(0xFF6B7280) // 灰色 - 待归档
                Constants.ElevatorStatus.ARCHIVED -> Color(0xFF6B7280) // 灰色 - 已归档
                else -> Color(0xFF6B7280) // 默认灰色
            }
            
            Card(
                colors = CardDefaults.cardColors(
                    containerColor = statusColor.copy(alpha = 0.1f)
                ),
                shape = RoundedCornerShape(12.dp)
            ) {
                Text(
                    text = statusText,
                    fontSize = 12.sp,
                    color = statusColor,
                    fontWeight = FontWeight.Medium,
                    modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp)
                )
            }
            
        }
    }
}
